package com.hao.leetcode;

import java.util.Stack;

public class Demo20 {
    public static void main(String[] args) {
        Demo20 demo = new Demo20();
        String s = "(){}[]";
        boolean flag = demo.isValid(s);
        System.out.println(flag);

        /*s = "()";
        flag = demo.isValid(s);
        System.out.println(flag);

        s = "(]";
        flag = demo.isValid(s);
        System.out.println(flag);

        s = "([)]";
        flag = demo.isValid(s);
        System.out.println(flag); */

        s = "){";
        flag = demo.isValid(s);
        System.out.println(flag);
    }

    public boolean isValid(String s) {
        if (s == null || "".equals(s)) {
            return true;
        }
        if (s.length() % 2 != 0) {
            return false;
        }

        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            //40 41 91 93 123 125
            char c = s.charAt(i);
            if (c == 40 || c == 91 || c == 123) {
                stack.push(c);
            } else {
                if(stack.empty()){
                    return false;
                }
                char stackTop = stack.pop();
                if ((c == 41 && stackTop != 40) || (c == 125 && stackTop != 123) || (c == 93 && stackTop != 91)) {
                    return false;
                }
            }
        }
        return stack.empty();
    }
}
